﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Threading.Tasks;

namespace ImageTagToolViewModel.Models
{
    /// <summary>
    /// Contains methods for managing file operations.
    /// </summary>
    public static class FileHandler
    {
        /// <summary>
        /// Getting data of a specific picture.
        /// </summary>
        public static Picture AnalyzePicture(string path)
        {
            string name;
            int length;
            int height;
            int width;
            int hRes;
            int vRes;
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (Bitmap bitmap = new Bitmap(fs))
                {
                    name = fs.Name;
                    length = (int)fs.Length;
                    height = bitmap.Height;
                    width = bitmap.Width;
                    hRes = (int)Math.Round(bitmap.HorizontalResolution);
                    vRes = (int)Math.Round(bitmap.VerticalResolution);
                }
            }

            return new Picture(name, length, width, height, hRes, vRes);
        }

        /// <summary>
        /// Searches for pictures in the given location.
        /// </summary>
        public static List<string> ScanForPictures(string location)
        {
            List<string> foundFiles = new List<string>();
            DirectoryInfo di = new DirectoryInfo(location);
            RecursiveScan(di, foundFiles);
            return foundFiles;
        }

        /// <summary>
        /// Scans recursively a folder to search for pictures.
        /// </summary>
        private static void RecursiveScan(DirectoryInfo di, List<string> foundFiles)
        {
            Parallel.ForEach(di.GetFiles(), f =>
            {
                string fileName = f.Name.ToLower();
                if (fileName.Contains(".jpg") || fileName.Contains(".png") || fileName.Contains(".bmp"))
                {
                    foundFiles.Add(f.DirectoryName + "\\" + f.Name);
                }
            });
            Parallel.ForEach(di.GetDirectories(), d =>
            {
                RecursiveScan(d, foundFiles);
            });
        }

        /// <summary>
        /// Determines whether the specified file exists.
        /// </summary>
        public static bool FileExists(string path)
        {
            return File.Exists(path);
        }
    }
}
